package com.youfang.sixthmedia.ui.center;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.ViewFlipper;

import ch.boye.httpclientandroidlib.androidextra.Base64;

import com.gzit.common.ModelAsyncTask;
import com.gzit.common.async.AsynCallback;
import com.gzit.utils.AndroidUtils;
import com.gzit.utils.StringUtils;
import com.youfang.sixthmedia.R;
import com.youfang.sixthmedia.common.YoufangContext;
import com.youfang.sixthmedia.controller.HeaderController;
import com.youfang.sixthmedia.message.GetuserbyusernameRequest;
import com.youfang.sixthmedia.message.GetuserbyusernameResponse;
import com.youfang.sixthmedia.message.center.SaveuserinfoRequest;
import com.youfang.sixthmedia.message.center.SaveuserinfoResponse;
import com.youfang.sixthmedia.message.model.User;
import com.youfang.sixthmedia.net.Net;
import com.youfang.sixthmedia.net.Response;

public class CProfileActivity extends Activity {

	private static final int PHOTO_WIDTH = 80;

	private ImageView photoView;

	private CProfileActivity that = this;

	private String newpic;
	boolean logoUpdated = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.c_profile_activity);

		photoView = (ImageView) this.findViewById(menuTriggerID);
		remoteLoadUserProfile();

		initMenu();

	}

	ViewFlipper menuFlipper;
	PopupWindow popupWindow;
	View menuLayout;
	int menuTriggerID = R.id.header;

	private void initMenu() {

		this.findViewById(menuTriggerID).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {

						showMenu();

					}
				});

		int layoutId = R.layout.menu_photo_select;
		menuFlipper = new ViewFlipper(this);
		menuFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
				R.anim.menu_in));
		menuFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
				R.anim.menu_out));
		menuFlipper.setFlipInterval(600000);
		menuLayout = this.getLayoutInflater().inflate(layoutId, null);
		menuFlipper.addView(menuLayout);
		// tvSave = (TextView) menuLocalSaveLayout.findViewById(R.id.save);
		// tvCancel = (TextView) menuLocalSaveLayout.findViewById(R.id.cancel);
		popupWindow = new PopupWindow(menuFlipper, LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT);
		popupWindow.setFocusable(true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.update();

		OnClickListener listener = new OnClickListener() {

			@Override
			public void onClick(View v) {
				hideMenu();
				switch (v.getId()) {
				case R.id.item1:
					startGallary();
					break;
				case R.id.item2:
					startCamera();
					break;
				case R.id.cancel:// cancel
					break;

				}

			}
		};

		for (int id : new int[] { R.id.item1, R.id.item2, R.id.cancel }) {
			menuLayout.findViewById(id).setOnClickListener(listener);

		}

	}

	private void showMenu() {

		if (popupWindow != null) {
			if (popupWindow.isShowing()) {
				popupWindow.dismiss();
			} else {
				setLayoutAlpha(this, 1f);
				popupWindow.showAtLocation(this.findViewById(menuTriggerID),
						Gravity.BOTTOM, 0, 0);
				menuFlipper.startFlipping();// 播放动画
			}
		}

	}

	public static void setLayoutAlpha(Activity activity, float alpha) {
		WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
		lp.alpha = alpha; // 0.0-1.0
		activity.getWindow().setAttributes(lp);
	}

	private void hideMenu() {
		popupWindow.dismiss();
		setLayoutAlpha(this, 1f);
	}

	// ////////////////////////////////////////
	// ////////////////////////////////////////////
	private void startCamera() {

		Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
		Bundle bundle = new Bundle();

		intent.putExtras(bundle);
		this.startActivityForResult(intent, CODE_CAMERA);

	}

	private void startGallary() {

		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType(MediaStore.Images.Media.CONTENT_TYPE);
		Intent chooser = Intent.createChooser(intent, "选择记账图片");
		// intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
		// MediaStore.Images.Media.CONTENT_TYPE);
		startActivityForResult(chooser, CODE_GALLARY);

	}

	private void startClearPic() {

	}

	// 将磁盘中的图标读成效图标,用于拍照按钮上的显示
	protected Bitmap readSmallCameraBitmap(String filename) {

		String fileName = YoufangContext.APP_DIR + filename;

		// Options既做为解码输入容器也做为输出容器，
		// 比如配置inJustDecodeBound=true的话，则可以从Options中取得outWidth和outHeight
		BitmapFactory.Options options = new Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(fileName, options);

		int considerSampleWidth = Math.min(options.outHeight, options.outWidth);

		// 只是为了在拍照按钮上显示一个大概36dip的图片，不需要将整个bitmap图片都加载到内存中，以免太耗资源
		// 采用等比例采样的方式取需要大小的位图即可
		BitmapFactory.Options bitmapOptions = new Options();
		bitmapOptions.inSampleSize = considerSampleWidth
				/ AndroidUtils.Screen.dp2pix(PHOTO_WIDTH);
		bitmapOptions.inJustDecodeBounds = false;

		Bitmap image = BitmapFactory.decodeFile(fileName, bitmapOptions);

		return image;

	}

	// 设置相机按钮的图片
	protected void setupPhotoImage(Bitmap bitmap) {

		photoView.setImageBitmap(bitmap);

		// bitmap.recycle();
		System.gc();

	}

	// 在后台异步压缩图片
	class CompressPic extends ModelAsyncTask<String, String, Boolean> {

		private Bitmap bitmap;
		private String fileName;

		// private long comsumeTime;

		public CompressPic(Activity activity, Bitmap bitmap) {
			super(activity);
			this.bitmap = bitmap;
			this.loadingMessageContent = "正在处理图片中，请稍候...";
		}

		@Override
		protected void onProgressUpdate(String... values) {
			super.onProgressUpdate(values);

			AndroidUtils.toastShort(values[0]);

		}

		@Override
		protected Boolean doInBackground(String... params) {

			OutputStream os = null;

			try {

				this.fileName = params[0];

				String fullFileName = YoufangContext.APP_DIR + fileName;
				File file = new File(fullFileName);
				if (!file.exists()) {
					file.createNewFile();
				}

				os = new FileOutputStream(fullFileName);

				System.gc();

				int width = AndroidUtils.Screen.dp2pix(PHOTO_WIDTH);
				Bitmap bitmap = AndroidUtils.Image.scaleImageTo(this.bitmap,
						width, width);
				bitmap.compress(CompressFormat.JPEG, 60, os);

			} catch (IOException e) {
				e.printStackTrace();
				this.publishProgress("保存图片失败，原因：" + e.getMessage());
				return false;

			} finally {
				if (os != null) {
					try {
						os.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}

			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {

			if (result) {

				// 设置新的图片名
				newpic = fileName;

				// 设置相机按钮的图片
				setupPhotoImage(this.bitmap);

			}
			super.onPostExecute(result);

		}
	}

	// // 从相册返回时，进行的异步任务
	class GallaryPicSaver extends ModelAsyncTask<String, String, Boolean> {

		private Uri uri;
		private String fileName;

		public GallaryPicSaver(Activity activity, Uri uri) {
			super(activity);
			this.uri = uri;
			this.loadingMessageContent = "正在处理图片中，请稍候...";
		}

		@Override
		protected void onProgressUpdate(String... values) {
			super.onProgressUpdate(values);

			AndroidUtils.toastShort(values[0]);

		}

		@Override
		protected Boolean doInBackground(String... params) {

			fileName = params[0];

			// 将URI中的图片拷贝到ydg的目的地址中
			String fullFileName = YoufangContext.APP_DIR + fileName;

			InputStream is = null;
			OutputStream os = null;

			try {
				ContentResolver resover = that.getContentResolver();

				File file = new File(fullFileName);
				if (!file.exists()) {
					file.createNewFile();
				}

				os = new FileOutputStream(fullFileName);
				is = resover.openInputStream(uri);
				IOUtils.copy(is, os);

			} catch (Exception e) {
				e.printStackTrace();
				this.publishProgress("读取相册图片失败!失败原因：" + e.getMessage());
				return false;

			} finally {

				if (is != null) {
					try {
						is.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}

				if (os != null) {
					try {
						os.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}

			}

			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {

			if (result) {

				// 拷贝成功，设置新图标标记
				// 设置新的图片名
				newpic = fileName;

				// 设置相机按钮的图片
				Bitmap bitmap = readSmallCameraBitmap(fileName);
				setupPhotoImage(bitmap);

				// compress pic to specific size
				CompressPic compressor = new CompressPic(that, bitmap);
				compressor.execute(fileName);

			}

			super.onPostExecute(result);

		}

	}

	// 确认是否要保存图片
	private void confimSavePic(final Uri uri) {

		final String picid = "" + YoufangContext.getUser().userid;
		ContentResolver resover = that.getContentResolver();
		try {
			// 图片大小限制
			long fileSize = resover.openInputStream(uri).available();
			if (fileSize > YoufangContext.MAX_PHOTO_SIZE) {
				AndroidUtils.Dialog.alert(that, "图片大小不能超过2M");
				return;
			}

		} catch (IOException e) {
			e.printStackTrace();
			return;
		}

		// 从mime中取得文件格式
		// 并制定后缀
		final String fileName = picid
				+ "."
				+ AndroidUtils.getImageFormatFromMIME(resover.getType(uri),
						"jpeg");

		try {
			AndroidUtils.Dialog.showPicConfim(that, uri, 200,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							System.gc();
							GallaryPicSaver saver = new GallaryPicSaver(that,
									uri);
							saver.execute(fileName);

						}

					});
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	// 确认是否要保存图片
	private void confimSavePic(final Bitmap bitmap) {

		final String picid = "" + YoufangContext.getUser().userid;
		final String fileName = picid + ".jpeg";

		AndroidUtils.Dialog.showPicConfim(this, bitmap,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {

						System.gc();
						CompressPic compressor = new CompressPic(that, bitmap);
						compressor.execute(fileName);

					}

				});

	}

	private static final int CODE_GALLARY = 1001;
	private static final int CODE_CAMERA = 1002;

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			final Intent i) {
		super.onActivityResult(requestCode, resultCode, i);

		if (resultCode != RESULT_OK) {
			return;
		}

		switch (requestCode) {

		case CODE_GALLARY: {// 从相册返回

			System.gc();
			System.gc();

			confimSavePic(i.getData());
			break;

		}

		case CODE_CAMERA: {

			String cascde = i.getExtras().getString("cascde");
			final Bitmap bitmap = (Bitmap) i.getExtras().get("data");
			confimSavePic(bitmap);
			break;
		}

		}

	}

	// /////////////////////////////
	// ////////////////////////////
	private void remoteLoadUserProfile() {

		GetuserbyusernameRequest req = new GetuserbyusernameRequest();
		req.setUsername(YoufangContext.getUser().username);
		Net.doSimpleHttpRemoter(req, new GetuserbyusernameResponse(),
				new AsynCallback<Response>() {

					@Override
					public void callback(Response r) {
						if (r.isFail()) {
							AndroidUtils.toastShort("无法加载个人信息");
							return;
						}

						updateUI((GetuserbyusernameResponse) r);

					}
				});

	}

	private void updateUI(GetuserbyusernameResponse resp) {

		// sync user info to context and pesist it;
		resp.syncToUser();

		((TextView) this.findViewById(R.id.name)).setText(resp.getUsername());
		((EditText) this.findViewById(R.id.email)).setText(resp.getEmail());
		((EditText) this.findViewById(R.id.phone)).setText(resp.getMobile());

		((EditText) this.findViewById(R.id.introduce)).setText(resp
				.getIntroduce());

		ImageView header = (ImageView) this.findViewById(R.id.header);
		Uri uri = HeaderController.Cache.getFromCache(resp.getUserid());
		if (uri != null) {
			header.setImageURI(uri);
		}
		boolean isPublic = resp.isIspublic();
		((RadioButton) this.findViewById(isPublic ? R.id.yesRB : R.id.noRB))
				.setChecked(true);

		// logo would be refresh when use launch the app and do auto login....
		// String url = resp.getLogourl();

		// reg click event...
		this.findViewById(R.id.updatebtn).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						remoteSaveuserinfo();
					}
				});
	}

	private void remoteSaveuserinfo() {

		// new pic existed so do base64 encode action
		String logodata = "";

		if ((!StringUtils.isBlank(this.newpic))
				&& new File(YoufangContext.APP_DIR + this.newpic).exists()) {

			try {
				logodata = new String(Base64.encode(FileUtils
						.readFileToByteArray(new File(YoufangContext.APP_DIR
								+ this.newpic)), Base64.DEFAULT));
				logoUpdated = true;
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

		SaveuserinfoRequest req = new SaveuserinfoRequest();
		req.setEmail(((EditText) this.findViewById(R.id.email)).getText()
				.toString());
		req.setIntroduce(((EditText) this.findViewById(R.id.introduce))
				.getText().toString());
		req.setIspublic(((RadioButton) this.findViewById(R.id.yesRB))
				.isChecked() ? User.PUBLIC_YES : User.PUBLIC_NO);

		if (!StringUtils.isBlank(logodata)) {
			req.setLogodata(logodata);
		}
		req.setNickname(((TextView) this.findViewById(R.id.name)).getText()
				.toString());

		req.setPhone(((EditText) this.findViewById(R.id.phone)).getText()
				.toString());
		req.setSex(YoufangContext.getUser().sex);

		Net.doHttpRemote(this, req, new SaveuserinfoResponse(),
				new AsynCallback<Response>() {

					@Override
					public void callback(Response r) {
						if (r.isFail()) {
							AndroidUtils.toastShort("更新个人信息失败");
							return;
						}

						// copy userid to header path
						// save use info into to context and pesist it...
						if (logoUpdated) {
							try {

								File dstFile = new File(
										HeaderController.Cache.cachePath
												+ YoufangContext.getUser().userid);

								FileUtils.copyFile(new File(
										YoufangContext.APP_DIR + newpic),
										dstFile);
							} catch (Exception e) {
								e.printStackTrace();
							}

						}

						AndroidUtils.toastShort("更新个人信息成功");

					

					}
				});

	}
}
